import { Component, OnInit, ViewChild, ChangeDetectorRef, Output, Inject, EventEmitter, forwardRef } from '@angular/core';
import { TabsetComponent } from 'ngx-bootstrap';
import { path } from '../../../../path.config';
import { FileUploader } from '../../../../../lib/ng2-file-upload';
import { AppComponent } from '../../../../app.component';

import { masterService } from '../../../../../lib/master.service';
import { saveVarService } from '../../../../../lib/saveVar.service';

import * as $ from 'jquery';

@Component({
    selector: 'app-goods-marking',
    templateUrl: './goods-marking.component.html',
    styleUrls: ['./goods-marking.component.css'],
    providers: [forwardRef(() => AppComponent)]
})
export class GoodsMarkingComponent implements OnInit {
    @ViewChild('tabs') public tabs: TabsetComponent;

    @Output() AddGoodsMark = new EventEmitter<any>();

    // 添加上传的图片
    private addImgItem = path.imagesUpload.apiUrl;
    public addListItem = path.goodsManage.markManage.addListItem;
    public addListItemWithSn = path.goodsManage.markManage.addListItemWithSn;
    public search =path.goodsManage.search;
    public loading = {
        confirm: false
    }
    public rows: Array<any> = [];
    public selectdRows: Array<any> = [];
    public selectdSn: Array<any> = [];

    // 表格数据头部标题
    public columns: Array<any> = [
        { title: '商品sn', name: 'sn' },
        { title: '商品名称', name: 'name' },
        { title: '操作', name: 'btn' }
    ];
    // 当前页码
    public page: any = 1;
    // 一共多少页
    public itemsPerPage: number = 10;
    // 分页最多显示的页数
    public maxSize: number = 5;
    // 总页数计数变化时，事件数等于总页数计数
    public numPages: number = 1;
    // 总共的列表项数
    public totalItems: number = 0;
    // 分页器的文本配置
    public localText = {
        firstBtn: '首页',
        lastBtn: '末页',
        previousBtn: '上一页',
        nextBtn: '下一页'
    }

    public filter: any = {
        pageSize: 5,
        pageIndex: 1,
        keyword: ''
    }

    constructor(public _masterService: masterService,
        public _saveVar: saveVarService,
        public cdRef: ChangeDetectorRef,
        @Inject(forwardRef(() => AppComponent)) public app: AppComponent) { }

    public ngOnInit() {
        this.searchGoods();
    }

    // 上传图片获取图片id
    public uploadPic = {};

    // 上传图片对象
    public ImgUploader: FileUploader = new FileUploader({
        url: this.addImgItem,
        method: 'post',
        itemAlias: 'uploadedFile'
    })

    // 上传excel对象
    public ExcelUploader: FileUploader = new FileUploader({
        url: this.addImgItem,
        method: 'post',
        itemAlias: 'uploadedFile'
    })

    public condition: any = {
        labelName: '',
        labelUrl: '',
        beginTime: '',
        endTime: '',
        labelType: 0,
        excelUrl: '',
        goodsSn : []
    };

    public confirmAdd() {
        // 确认添加非空验证
        if (this.condition.labelType == 0) {
            this.condition.beginTime = $('#start1').val();
            this.condition.endTime = $('#end1').val();
            if (!this.condition.labelName) {
                this.app.toastWarning('请输入文字！');
                return;
            } else if (this.condition.labelName.length > 2) {
                this.app.toastWarning('文字标签不得超过两个字！');
                return;
            } else if (!this.condition.beginTime) {
                this.app.toastWarning('请选择开始时间！');
                return;
            } else if (!this.condition.endTime) {
                this.app.toastWarning('请选择结束时间！');
                return;
            } else if ($('#start1').val() > $('#end1').val()) {
                this.app.toastWarning('结束时间不得小于开始时间！');
                return;
            }
        } else if (this.condition.labelType == 1) {
            this.condition.beginTime = $('#start2').val();
            this.condition.endTime = $('#end2').val();
            if (!this.condition.labelUrl) {
                this.app.toastWarning('请上传图片！');
                return;
            } else if (!this.condition.beginTime) {
                this.app.toastWarning('请选择开始时间！');
                return;
            } else if (!this.condition.endTime) {
                this.app.toastWarning('请选择结束时间！');
                return;
            } else if ($('#start2').val() > $('#end2').val()) {
                this.app.toastWarning('结束时间不得小于开始时间！');
                return;
            }
        }

        let isSelectGoods = this.condition.goodsSn.length > 0
        if(isSelectGoods && this.condition.excelUrl){
            this.app.toastWarning('上传excel、直接选择商品两种方式只能选择一种！')
            return;
        }

        if (!isSelectGoods && !this.condition.excelUrl) {
            this.app.toastWarning('请上传excel或者选择需要打标的商品！')
            return;
        }

        let url = isSelectGoods ? this.addListItemWithSn : this.addListItem;

        this.loading.confirm = true

        // 确认添加
        this._masterService
            .postData(url, this.condition)
            .subscribe(res => {
                this.loading.confirm = false

                if (res.statusCode == 200) {
                    if (!res.data.errorIndex) {
                        this.app.toastSuccess('总共: ' + res.data.totalCnt + ' , 成功: ' + res.data.successCnt);
                    } else {
                        this.app.toastSuccess('总共: ' + res.data.totalCnt + ' , 成功: ' + res.data.successCnt + ' , 第' + res.data.errorIndex + '行出错', 10000);
                    }
                    this.AddGoodsMark.emit();
                    this.tabs.tabs[0].active = true;
                    this.selectActive(0);
                    $('#start1').val('');
                    $('#end1').val('');
                    // 清空新建框
                    this.condition = {
                        labelName: '',
                        labelUrl: '',
                        beginTime: '',
                        endTime: '',
                        labelType: 0,
                        excelUrl: '',
                        goodsSn: []
                    };
                    $('#ImgUploader').val('');
                    $('#ExcelUploader').val('');
                    this.ImgUploader.queue = [];
                    this.ExcelUploader.queue = [];
                    this.rows.forEach(curRow => {
                        curRow.isChecked = false
                    })
                    this.cdRef.detectChanges();
                } else if (res.statusCode == 401) {
                    this.app.logOff();
                } else {
                    this.app.toastError('错误信息: ' + res.errorMessage)
                }
            })
    }

    // 选择标签tab
    // 0为文字标签， 1为图片标签
    selectActive(type) {
        this.condition.labelType = type;
        if (type == 0) {
            $('#start2').val('');
            $('#end2').val('');
            this.condition.labelType = 0;
            this.condition.labelUrl = '';
        } else if (type == 1) {
            $('#start1').val('');
            $('#end1').val('');
            this.condition.labelType = 1;
            this.condition.labelName = '';
        }
    }

    // 上传方法
    // 0为图片， 1为excel
    uploadFile(uploader?, uploadType?) {
        if(this.condition.goodsSn.length > 0){
            this.app.toastWarning('直接选择商品之后无法上传excel！')
            return;
        }
        let thisItem = (uploader.length == 1) ? uploader.queue[0] : uploader.queue[uploader.queue.length - 1];
        if (thisItem == undefined) {
            if (uploadType == 0) {
                this.app.toastWarning('请上传图片！');
            } else if (uploadType == 1) {
                this.app.toastWarning('请上传excel！');
            }
            return;
        }
        let that = this;
        // 上传文件后缀
        let suffix = thisItem.some.name.substr(thisItem.some.name.lastIndexOf('.') + 1)


        // 上传图片验证
        if (uploadType == 0 && !(suffix == 'jpg' || suffix == 'png' || suffix == 'gif')) {
            this.app.toastWarning('请上传jpg、png、gif格式图片！');
            return;
        }

        // 上传excel验证
        if (uploadType == 1 && suffix != 'xlsx') {
            this.app.toastWarning('请上传excel');
            return;
        }

        thisItem.withCredentials = false;
        // 成功回调
        thisItem.onSuccess = function (response, status) {
            // 上传文件成功
            if (status == 200) {
                // 上传文件后获取服务器返回的数据
                let tempRes = JSON.parse(response);
                if (uploadType == 0) {
                    that.condition.labelUrl = tempRes.data.url[0];
                } else if (uploadType == 1) {
                    that.condition.excelUrl = tempRes.data.url[0];
                }
                that.app.toastSuccess('上传成功！');
            } else {
                // 上传文件后获取服务器返回的数据错误
                that.app.toastError('错误信息：' + response.errorMessage)
            }
        };

        thisItem.onError = function (response) {
            // 错误回调
            that.app.toastError('错误信息：' + response.errorMessage);
        };
        thisItem.upload(); // 开始上传
    }

    // 搜索商品信息
    searchGoods(urlObj?) {
        if (urlObj) {
            this.filter.pageSize = urlObj.itemsPerPage;
            this.filter.pageIndex = urlObj.page;
        } else {
            this.filter.pageSize = 5;
            this.filter.pageIndex = 1;
        }

        this._masterService
            .getData(this.search, this.filter)
            .subscribe((res) => {
                if (res.statusCode == 200) {
                    res.data.items.forEach(curRow => {
                        let isChecked = this.condition.goodsSn.some(curGoods => {
                            return curRow.sn === curGoods.sn
                        })

                        curRow.isChecked = isChecked
                    })
                    this.rows = res.data.items.concat()
                    this.totalItems = res.data.pagination.totalCount;
                    this.itemsPerPage = res.data.pagination.pageSize;
                    this.page = parseInt(res.data.pagination.pageIndex);
                    this.cdRef.detectChanges();
                } else if (res.statusCode == 401) {
                    this.app.logOff();
                } else {
                    this.app.toastError('错误信息： ' + res.errorMessage);
                }
            });
    }

    selectGoods(index, curRow) {  // 选择商品
        if (this.condition.excelUrl) {
            this.app.toastWarning('上传excel之后无法直接选择商品！')
            return;
        }

        if (this.rows[index].isChecked) {
            return;
        }

        let isRepeat = this.condition.goodsSn.some(item => {
            if(item.sn === curRow.sn) {
                return true
            }
        })

        if (!isRepeat) {
            this.condition.goodsSn.push(curRow)
            this.rows[index].isChecked = true
        } else {
            this.app.toastWarning('已选择该商品，请勿重复添加！')
        }
    }

    removeGoods(row){ // 移除已选择的商品
        let index = this.condition.goodsSn.findIndex(ele => {
            this.rows.forEach(curRow => {
                if (curRow.sn === row.sn) {
                    curRow.isChecked = false
                }
            })
            return row.sn === ele.sn
        })

        this.condition.goodsSn.splice(index, 1)
    }

    selectedFileOnChanged(event: any, uploader) {
        let thisItem = uploader.queue[0] = uploader.queue[uploader.queue.length - 1];
        let reader = new FileReader();
        reader.onload = function (e) {
            thisItem.src = this.result;
        }
        this.cdRef.detectChanges();
    }
}
